// user marker
function userMarker(id, name, address, description, longitude, latitude, type,
		author, visible) {
	this.id = id;
	this.name = name;
	this.address = address;
	this.description = description;
	this.longitude = longitude;
	this.latitude = latitude;
	this.type = type;
	this.author = author;
	this.visible = visible;
}

MarkerTypes = {
	types : [ "ACCIDENT", "RADAR", "TRAFFIC", "PLACE", "ADVERT" ],
	ACCIDENT : "ACCIDENT",
	RADAR : "RADAR",
	TRAFFIC : "TRAFFIC",
	PLACE : "PLACE",
	ADVERT : "ADVERT",

	getSelectBox : function(lang, type) {
		var types = [];
		if (lang == "pl") {
			types = [ "Wypadek", "Radar", "Korek", "Miejsce", "Reklama" ];
		}
		if (lang == "en") {
			types = [ "Accident", "Radar", "Traffic", "Place", "Advertisement" ];
		}
		var select = '<select name="type" class="markerTypes">';
		
		for ( var i = 0; i < types.length; i++) {
			
			if(type == MarkerTypes.types[i])
			{
				select += '<option selected="selected" value="' + MarkerTypes.types[i] + '">'
						+ types[i] + "</option>";
			}
			else
			{
				select += '<option value="' + MarkerTypes.types[i] + '">'
				+ types[i] + "</option>";
			}
		}
		select += '</select>';
		return select;
	},

	getIcon : function(type) {
		switch(type) {
		case MarkerTypes.ACCIDENT : return 'resources/css/img/icons/wypadek.png';
		case MarkerTypes.PLACE : return 'resources/css/img/icons/miejsce.png';
		case MarkerTypes.RADAR : return 'resources/css/img/icons/fotoradar.png';
		case MarkerTypes.TRAFFIC : return 'resources/css/img/icons/korki.png';
		case MarkerTypes.ADVERT : return 'resources/css/img/icons/reklama.png';
		};
	}
};

function getAddressFromLatLng(latLng) {

    $("#marker_latitude").val(latLng.lat());
    $("#marker_longitude").val(latLng.lng());
	
	var address = "";

	geocoder = new google.maps.Geocoder();

	geocoder.geocode({
		'latLng' : latLng
	}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if (results[0]) {
				address = results[0].formatted_address;

				$(".currentAddress").html(address);
				$("#marker_address").val(address);


			}
		} else {
			alert("Geocoder failed due to: " + status);
		}
	});
}

// MARKER MANAGER
MarkerManager = {

	map : null,

	markerImage : new google.maps.MarkerImage(null,
	// This marker is 20 pixels wide by 32 pixels tall.
	new google.maps.Size(32, 32),
	// The origin for this image is 0,0.
	new google.maps.Point(0, 0),
	// The anchor for this image is the base of the flagpole at 0,32.
	new google.maps.Point(16, 16)),

	markerShape : {
		coord : [ 0,0, 32,32 ],
		type : 'rect'
	},
	
	currentAction : "add",

	userMarkers : [],

	infoWindows : [],
	
	markers : [],

	currentInfoWindow : null,

	intervalSet : false,
	
	interval : 60000,

	initialize : function(map) {

		MarkerManager.map = map;

		MarkerManager.refreshMarkers();
		
		if (!MarkerManager.intervalSet) {
			// repeat each 30 seconds
			window.setInterval(function() {
				MarkerManager.refreshMarkers();
			}, MarkerManager.interval);
			MarkerManager.intervalSet = true;
		}
		
		// bind submit
		$("#dropdownMarkerAddEditForm").bind('submit', function(event){

			//add marker to map
			var values = {};
			$.each($('#dropdownMarkerAddEditForm').serializeArray(), function(i, field) {
			    values[field.name] = field.value;
			});

			MarkerManager.removeMarker(MarkerManager.lastCreatedMarker);
			
			var newUserMarker = new userMarker(-100, values["name"], values["address"], values["description"], values["longitude"], values["latitude"], values["type"], username);
			MarkerManager.addMarker(newUserMarker);
			
			//send marker to server
			var data = $('#dropdownMarkerAddEditForm').serialize();
			
			if(MarkerManager.currentAction == "add")
			{
				Api.me.addMarker(data, function(){
						NotificationManager.defaultNotification(I18N.msg.markerAddTitle, I18N.msg.markerAddText);
						$("#markerAddEditDialog").dialog("close");
						MarkerManager.refreshMarkers();
					},
					function(){
						NotificationManager.alertNotification(I18N.msg.markerAddErrorTitle, I18N.msg.markerAddErrorText);
					});
			}
			else if(MarkerManager.currentAction == "edit")
			{
				var json = $.toJSON(values);
				data = "_method=PUT&marker=" + json;
				
				Api.me.editMarker(values["id"], data, function(){
						NotificationManager.defaultNotification(I18N.msg.markerEditTitle, I18N.msg.markerEditText);
						$("#markerAddEditDialog").dialog("close");
						MarkerManager.refreshMarkers();
					},
					function(){
						NotificationManager.alertNotification(I18N.msg.markerEditErrorTitle, I18N.msg.markerEditErrorText);
					});
			}
			
			MarkerManager.currentAction = "add";
			
			return false;
		});
	},

	refreshMarkers : function() {

		MarkerManager.removeMarkers();
		
		Api.me.getMarkers(function(data) {

			MarkerManager.userMarkers = [];

			if(data.length > 0)
			{
				$.each(data, function(key, val) {
					var usermarker = new userMarker(val.id, val.name, val.address,
							val.description, val.longitude, val.latitude, val.type,
							val.author);
					MarkerManager.userMarkers.push(usermarker);
				});
				MarkerManager.setMarkers();
			}
		});
	},

	removeMarkers : function() {
		//removing markers
		if(MarkerManager.markers.length > 0)
		{
			for( var i = 0; i < MarkerManager.markers.length; i++)
			{
				if(MarkerManager.markers[i].getZIndex() != -10) // if marker is not currently added
					MarkerManager.markers[i].setMap(null);
			}
		}
	},
	
	showMarkers : function() {
		if(MarkerManager.markers.length > 0)
		{
			for( var i = 0; i < MarkerManager.markers.length; i++)
				this.markers[i].setMap(this.map);
		}
	},
	
	hideMarkers : function() {
		if(MarkerManager.markers.length > 0)
		{
			for( var i = 0; i < MarkerManager.markers.length; i++)
				this.markers[i].setMap(null);
		}
	},
	
	setMarkers : function() {

		var markers = MarkerManager.userMarkers;

		MarkerManager.infoWindows = [];
		
		MarkerManager.removeMarkers();
		MarkerManager.markers = [];

		for ( var i = 0; i < markers.length; i++) {
			MarkerManager.addMarker(markers[i]);
		}

		// close infowindows on map click
		google.maps.event.addListener(MarkerManager.map, 'click', function() {
			if (MarkerManager.currentInfoWindow != null)
				MarkerManager.currentInfoWindow.close();
		});
		
		
	},

	lastCreatedMarker : null,

	addMarker : function(newUserMarker) {
		
		function infoCallback(infowindow, marker) {
			return function() {

				if (MarkerManager.currentInfoWindow != null)
					MarkerManager.currentInfoWindow.close();

				infowindow.open(MarkerManager.map, marker);
				MarkerManager.currentInfoWindow = infowindow;
			};
		}
		
		var myLatLng = new google.maps.LatLng(newUserMarker.latitude,
				newUserMarker.longitude);

		var marker = new google.maps.Marker({
			position : myLatLng,
			map : MarkerManager.map,
			// shadow : shadow,
			icon : 	MarkerTypes.getIcon(newUserMarker.type),
			shape : MarkerManager.markerShape,
			title : newUserMarker.name,
			zIndex : newUserMarker.id
		});
		
		//marker.getIcon().url = MarkerTypes.getIcon(newUserMarker.type);
		
		MarkerManager.markers.push(marker);

		var contentDiv = "<div class=\"infoWindow\">"
				+ "<br><h3>" + newUserMarker.name + "</h3><p>"
				+ newUserMarker.description + '</p>' + 
				'<div class="left">' + 
				'<button class="btn" type="submit"><div><span id="editMarker_' + newUserMarker.id + '" class="editMarker">' + I18N.msg.markerEdit + 
				'</span></div></button></div><div class="right">' +
				'<button class="btn" type="submit"><div><span id="deleteMarker_' + newUserMarker.id + '" class="deleteMarker">' + I18N.msg.markerDelete + '</span></div></button></div>' + 
				'<div class="clear"></div></div>';

		// edit marker
		$('#editMarker_' + newUserMarker.id).die('click').live('click', function(){
			//alert('edit ' + newUserMarker.id);
			MarkerManager.editMarker(marker);
		});
		
		//delete marker
		$('#deleteMarker_' + newUserMarker.id).die('click').live('click', function(){
			//alert('delete ' + newUserMarker.id);
			MarkerManager.removeMarkerFromSystem(marker);
		});
		
		var infowindow = new google.maps.InfoWindow({
			content : contentDiv
		});

		MarkerManager.infoWindows.push(infowindow);

		google.maps.event.addListener(marker, 'click', infoCallback(
				infowindow, marker, MarkerManager.map));
		
		MarkerManager.lastCreatedMarker = marker;
	},
	
	removeMarker : function(marker) {
		if(MarkerManager.markers.length > 0)
		{
			for( var i = 0; i < MarkerManager.markers.length; i++)
			{
				if(MarkerManager.markers[i].getPosition() == marker.getPosition())
				{
					MarkerManager.markers[i].setMap(null);
					MarkerManager.markers.slice(i, 1);
				}
			}
		}
	},
	
	removeMarkerFromSystem : function(marker) {
		$( "#confirmMarkerDeleteDialog" ).dialog({
			resizable: false,
			height:140,
			modal: true,
			buttons: {
				"Usuń": function() {
					MarkerManager.removeMarker(marker);
					Api.me.deleteMarker(marker.getZIndex(), function(){
						NotificationManager.defaultNotification(I18N.msg.markerDeleteTitle, I18N.msg.markerDeleteText);
					}, function(){
						NotificationManager.alertNotification(I18N.msg.markerDeleteErrorTitle, I18N.msg.markerDeleteErrorText);
					});
					
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	},
	
	editMarker : function(marker) {
		
		Api.me.getMarker(marker.getZIndex(), function(data) {

			$("#marker_id").val(data.id);
			$("#marker_name").val(data.name);
			
			$(".currentAddress").html(data.address);
			$("#marker_address").val(data.address);
			
			$("#marker_description").val(data.description);
			$("#marker_longitude").val(data.longitude);
			$("#marker_latitude").val(data.latitude);
			
			$("#marker_types").html(MarkerTypes.getSelectBox("pl", data.type));
			
			$("#marker_author").val(data.author);
			
			MarkerManager.currentAction = "edit";
		});
		
		$("#markerAddEditDialog").dialog("open");
	}

};

// MAPS MANAGER
MapsManager = {

	mapOptions : {
		zoom : 15,
		center : new google.maps.LatLng(52.408297, 16.933365),
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		panControl : false,
		scaleControl : true,
		streetViewControl : false,
		zoomControlOptions : {
			position : google.maps.ControlPosition.LEFT_TOP,
			style : google.maps.ZoomControlStyle.LARGE
		}
	},

	map : null,

	initialize : function() {
		if (!MapsManager.map) {
			MapsManager.map = new google.maps.Map(document
					.getElementById("map-canvas"), MapsManager.mapOptions);
		} else {
			MapsManager.refresh();
		}

		// get markers
		if (isLogged == 'true') {
			MarkerManager.initialize(MapsManager.map);
			FriendsManager.initialize(MapsManager.map);
		}

		MapsManager.overlay = new google.maps.OverlayView();
		MapsManager.overlay.draw = function() {
		};
		MapsManager.overlay.setMap(MapsManager.map);
	},

	refresh : function() {
		$('#map-canvas').parent().html(MapsManager.map.getDiv());
	},

	overlay : null
};

function editMarkerClick(marker)
{

};
